import moment from 'moment'
import AntModal from '@/components/pt/dialog/AntModal'
import ImageUpload from '@/components/pt/imageUpload/ImageUpload'
import Editor from '@/components/pt/editor/Editor'
import SelectUser from '@/components/pt/selectUser/SelectUser'
import SelectSection from '@/views/platform/components/SelectSection'
import { getPost, addPost, updatePost } from '@/api/platform/post'
import { getUser, getUserProfile } from '@/api/system/user'

export default {
  name: 'CreateForm',
  props: {
    statusOptions: {
      type: Array,
      required: true
    },
    anonymityOptions: {
      type: Array,
      required: true
    },
    typeOptions: {
      type: Array,
      required: true
    }
  },
  components: {
    AntModal,
    ImageUpload,
    Editor,
    SelectUser,
    SelectSection
  },
  data() {
    return {
      open: false,
      closeDialog: true,
      spinning: false,
      delayTime: 100,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      contentEditorEdit: '',
      loading: false,
      disabled: false,
      chooseUserDisabled: true,
      total: 0,
      id: undefined,
      formTitle: '添加帖子管理',
      // 表单参数
      form: {},
      rules: {
        userId: [{ required: true, message: '请选择用户', trigger: 'blur' }],
        sectionId: [{ required: true, message: '请选择版块', trigger: 'blur' }],
        title: [{ required: true, message: '帖子标题不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '请选择帖子类型', trigger: 'blur' }],
        content: [{ required: true, message: '帖子内容不能为空', trigger: 'blur' }],
        anonymity: [{ required: true, message: '请选择匿名状态', trigger: 'blur' }],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请正确填写手机号',
            trigger: 'blur'
          }
        ]
      },
      dateFormat: 'YYYY-MM-DD HH:mm:ss'
    }
  },
  filters: {},
  created() {},
  computed: {},
  watch: {},
  mounted() {},
  methods: {
    moment,
    disabledDatePublish(current) {
      return current && current < moment().subtract(1, 'days').endOf('day')
    },
    range(start, end) {
      const result = []
      for (let i = start; i < end; i++) {
        result.push(i)
      }
      return result
    },
    disabledTimePublish(current) {
      let strtime
      let newTime
      current ? (strtime = new Date(current._i.replace(/-/g, '/'))) : (strtime = moment())
      current ? (newTime = moment()) : (newTime = moment().add(1, 'days').startOf('day'))
      const hours = moment().hours() //0~23
      const minutes = moment().minutes() //0~59
      const seconds = moment().seconds() //0~59 //当日只能选择当前时间之后的时间点
      if (strtime <= newTime) {
        return {
          disabledHours: () => this.range(0, 23).splice(0, hours),
          disabledMinutes: () => this.range(0, 59).splice(0, minutes),
          disabledSeconds: () => this.range(0, 59).splice(0, seconds)
        }
      }
    },
    disabledDateEdit(current) {
      if (this.form.publishTime) {
        return current < moment(this.form.publishTime)
      } else {
        return current && current < moment().subtract(1, 'days').endOf('day')
      }
    },
    disabledTimeEdit() {
      let dateTime = moment()
      if (this.form.publishTime) {
        dateTime = moment(this.form.publishTime)
      } else {
        dateTime = moment(new Date())
      }
      const hours = dateTime.hours() //0~23
      const minutes = dateTime.minutes() //0~59
      const seconds = dateTime.seconds() //0~59
      return {
        disabledHours: () => this.range(0, 24).splice(0, hours),
        disabledMinutes: () => this.range(0, minutes),
        disabledSeconds: () => this.range(0, seconds)
      }
    },
    onClose() {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        userId: undefined,

        regionId: undefined,

        sectionId: undefined,

        title: undefined,

        content: undefined,

        image: undefined,

        contact: undefined,

        phone: undefined,

        address: undefined,

        anonymity: '0',

        type: '0',

        publishTime: undefined,

        editTime: undefined,

        likeNumber: 0,

        collectNumber: 0,

        replyNumber: 0,

        viewNumber: 0,

        reportNumber: 0,

        status: '0'
      }
    },
    roleControl() {
      if (!this.$store.state.user.roles.includes('admin')) {
        this.chooseUserDisabled = false
        return true
      }
      return false
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.formTitle = '添加帖子管理'
      this.open = true
      this.form.content = ''
      if (this.roleControl()) {
        getUserProfile().then(response => {
          this.form.userId = { ids: response.data.user.id, names: response.data.user.name }
        })
      }
      this.$nextTick(() => {
        this.$refs.editor.init()
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.open = true
      this.spinning = !this.spinning
      const postId = row.id
      if (row.sectionId !== null) {
        this.form.sectionId = { regionId: row.regionId, sectionId: row.sectionId }
      }
      getPost(postId).then(response => {
        this.form = response.data
        if (!this.roleControl()) { 
          if (this.form.userId !== null) {
            getUser(this.form.userId).then(res => {
              this.form.userId = { ids: this.form.userId, names: res.data.name }
            })
          }
        }
        if (this.form.sectionId !== null) {
          this.form.sectionId = { regionId: this.form.regionId, sectionId: this.form.sectionId }
        }

        this.$refs.editor.init(this.form.content)
        this.formTitle = '修改帖子管理'
        this.spinning = !this.spinning
      })
    },
    setForm() {
      this.form.content = this.$refs.editor.getValue()
      if (!this.form.publishTime) {
        this.form.publishTime = moment(new Date()).format(this.dateFormat)
      }
      if (this.form.id !== undefined) {
        this.form.editTime = moment(new Date()).format(this.dateFormat)
      }
    },
    /** 提交按钮 */
    submitForm: function (closeDialog) {
      this.closeDialog = closeDialog
      this.disabled = true
      this.setForm()
      this.$refs.form.validate(valid => {
        if (valid) {
          const saveForm = JSON.parse(JSON.stringify(this.form))
          if (this.form.userId !== null && this.form.userId !== undefined) {
            saveForm.userId = this.form.userId.ids
          }
          if (this.form.sectionId !== null && this.form.sectionId !== undefined) {
            saveForm.sectionId = this.form.sectionId.sectionId
            saveForm.regionId = this.form.sectionId.regionId
          }
          if (this.form.id !== undefined) {
            updatePost(saveForm)
              .then(response => {
                this.$message.success('更新成功', 3)
                this.open = false
                this.$emit('ok')
                this.$emit('close')
                this.disabled = false
              })
              .catch(error => {
                this.disabled = false
              })
          } else {
            addPost(saveForm)
              .then(response => {
                this.$message.success('新增成功', 3)
                this.open = false
                this.$emit('ok')
                this.$emit('close')
                this.disabled = false
              })
              .catch(error => {
                this.disabled = false
              })
          }
        } else {
          this.disabled = false
          return false
        }
      })
    },
    back() {
      const index = '/platform/post/index'
      this.$router.push(index)
    }
  }
}
